package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.*;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import com.usian.wemedia.service.WmUserService;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmUserService wmUserService;


    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE=1 ;//主图引用

    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {

        //1.参数检查
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getKeyword()!=null && dto.getKeyword()!=""){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        if (dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmNews::getUserId,user.getId());
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        Page page = new Page(dto.getPage(),dto.getSize());
        IPage result = page(page,lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1:校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(isSubmit ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2:解析json --》wmnews  保存wmnews表
        WmNews wmNews =new WmNews();
        //2.1 对象浅拷贝 从哪源头copy 那里目标
        BeanUtils.copyProperties(dto,wmNews);
        //2.2: 封面是自动，那就type赋值为null
        if(WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //2.3：处理解析封面图片
        if(dto.getImages()!=null && dto.getImages().size()>0){
            String s = dto.getImages().toString().replace("[", "").replace("]", "")
                    .replace(fileServerUrl, "").replace(" ", "");
            wmNews.setImages(s);
        }
        //2.4:保存新闻表
        wmNews.setCreatedTime(new Date());
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wmNews.setUserId(user.getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if(wmNews.getId()==null){
            this.save(wmNews);
        }else{
            this.updateById(wmNews);
            //把素材与文章关系表关系删除   先删后新增
            QueryWrapper<WmNewsMaterial> queryWrapper =new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
        }

        //3:素材表  替换 解析   保存素材表
        String content = dto.getContent();
        //3.1 json转换为list集合
        List<Map> imageList =JSON.parseArray(content, Map.class);
        //3.2: 提取内容中图片
        List<String> ectractUrlInfo = this.ectractUrlInfo(imageList);

        //4: 批量保存关系表
        if(isSubmit.equals( WmNews.Status.SUBMIT.getCode())&& ectractUrlInfo.size()>0){

            //调用保存文章和素材关系表
            ResponseResult result = this.saveRelativeInfoForContent(ectractUrlInfo, wmNews.getId());
            if ( result.getCode()!=0) {
                return result;
            }
        }

        //5:设置封面
        if(isSubmit.equals( WmNews.Status.SUBMIT.getCode())){
            ResponseResult result = this.saveRelativeInfoForCover(dto, ectractUrlInfo, wmNews);
            if ( result.getCode()!=0) {
                return result;
            }
        }

        kafkaTemplate.send("wemediaAutoScan",JSON.toJSONString(wmNews.getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //提取封面图片且维护封面和素材表之间的关系
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto,List<String> imageList, WmNews wmNews){
        //1:判断多图 一图 修改主表字段
        List<String> imageListNew =dto.getImages();
        if(dto.getType().equals(WM_NEWS_TYPE_AUTO)){
            if(imageList.size()>0 &&imageList.size()<=2){
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                imageListNew =imageList.stream().limit(1).collect(Collectors.toList());
            }else if(imageList.size()> 2){
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                imageListNew =imageList.stream().limit(3).collect(Collectors.toList());
            }else{
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }
        String imageStr=null;
        if(imageListNew.size()>0){
            imageStr =imageListNew.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", "");

            wmNews.setImages(imageStr);
        }
        this.updateById(wmNews);

        //2:维护封面图片和素材的关系
        List<String> imageListNew1=new ArrayList<>();
        for(String s :imageListNew){
            imageListNew1.add(s.replace(fileServerUrl, ""));
        }
        ResponseResult responseResult = this.saveRelativeInfoForContent(imageListNew1, wmNews.getId());
        return responseResult;
    }

    //保存素材关系表
    private ResponseResult saveRelativeInfoForContent(List<String> imageList,Integer wmNewsId){
        //1:判断提取出来的图片是否存在与素材库中
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl,imageList);
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getId());
        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(lambdaQueryWrapper);

        //2:如果存在，二次过滤真实存在与素材库的图片提取，存新的List《String》
        List<String> wmMaterialListNew =new ArrayList<>();
        if(wmMaterialList.size()>0){
            //3: 给每条数据构建模型，map集合 key==url  value==素材id
            Map<String, Integer> map = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            //4: 循环wmMaterialList 过滤摸鱼的
            for(String s :imageList){
                Integer wmId = map.get(s);
                if(wmId==null){
                    //这是个摸鱼 库中没有的
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                }else{
                    wmMaterialListNew.add(wmId.toString());
                }
            }
        }
        //5:保存中间表
        wmNewsMaterialMapper.saveRelationsByContent(wmMaterialListNew,wmNewsId,WM_NEWS_CONTENT_REFERENCE);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //自定义提取文章内容中的图片
    private List<String> ectractUrlInfo(List<Map> mapList){
        List<String> imageList = new ArrayList<>();
        for(Map map:mapList){
            if(map.get("type").equals(WM_NEWS_TYPE_IMAGE)){
                String imageUrl = (String) map.get("value");
                imageList.add(imageUrl.replace(fileServerUrl,""));
            }
        }
        return imageList;
    }

    @Override
    public ResponseResult findByNewId(Integer id) {
        if(id ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult deleteByNewId(Integer id) {
        if(id ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        this.removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        if (dto.getEnable()!=null && (dto.getEnable()==1 || dto.getEnable() == 0)){
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,dto.getId()));

            Map<String,Object> mesMap = new HashMap<>();
            mesMap.put("enable",dto.getEnable());
            mesMap.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send("newsDownOrUp",JSON.toJSONString(mesMap));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateNewStatus(WmNews wmNews) {
        if (wmNews==null && wmNews.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        boolean b = this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getStatus, wmNews.getStatus())
                .set(WmNews::getArticleId, wmNews.getArticleId()).set(WmNews::getReason, wmNews.getReason())
                .eq(WmNews::getId, wmNews.getId()));

//        boolean b = this.updateById(wmNews);
        if (b){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public List<Integer> findNews() {
        List<WmNews> wmNewsList = wmNewsMapper.selectList(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8));

        List<Integer> list = wmNewsList.stream().map(WmNews::getId).collect(Collectors.toList());
        return list;
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();

        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        List<WmNewsVo> newsVoList = wmNewsMapper.findList(dto);

        int count = wmNewsMapper.findCount(dto);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(newsVoList);
        return responseResult;
    }

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {

        if (id == null){
            return null;
        }

        WmNews wmNews = getById(id);

        WmUser wmUser = null;
        if (wmNews != null && wmNews.getUserId()!=null){
             wmUser = wmUserService.getById(wmNews.getUserId());
        }

        WmNewsVo wmNewsVo = new WmNewsVo();

        BeanUtils.copyProperties(wmNews,wmNewsVo);

        wmNewsVo.setAuthorName(wmUser.getName());

        return wmNewsVo;
    }


}
